import { withMiddleware } from '../../../../lib/middleware/entry';
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import bcrypt from 'bcryptjs';
import { generateToken } from '@/utils/jwt';
import { LoginRequest, LoginResponse } from '@/types/auth';

// POST /api/admin/auth/login - 用户登录
 async function handlePost(request: NextRequest) {
    const body: LoginRequest = await request.json();

    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { username: body.username },
          { email: body.username },
        ],
      },
    });

    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 });
    }

    const isPasswordValid = await bcrypt.compare(body.password, user.password);
    if (!isPasswordValid) {
      return NextResponse.json({ error: '密码错误' }, { status: 401 });
    }

    if (user.status !== 1) {
      return NextResponse.json({ error: '账号已被禁用' }, { status: 403 });
    }

    const { password, ...userInfo } = user;
    const token = generateToken(user);

    return {
      token,
      user: userInfo,
    }

}

export const POST = withMiddleware(handlePost);
